//
//  DLMachineKeyboardView.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/11/26.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLMachineKeyboardView.h"


@interface DLMachineKeyboardView()<UITextViewDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UIView *voiceView;

@property (nonatomic, copy) NSString *resultStringFromJson;

@property (nonatomic, strong) UIImageView *imageV;

@property (nonatomic, assign) NSInteger microphoneState;

@end

@implementation DLMachineKeyboardView

- (instancetype) initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        [self layoutSubControls];
        self.resultStringFromJson = @"";
        self.backgroundColor = [UIColor redColor];
        self.backgroundColor = kDLMachineTableAndCellBgColor;
    }
    return self;
}
- (void) layoutSubControls {
    
    
    UIImageView *textBgImageView = [UIImageView new];
    textBgImageView.frame = CGRectMake(0, kAutoWidth(6.5), kAutoWidth(322), kAutoWidth(71));
    textBgImageView.image = [UIImage imageNamed:@"machine_textViewBg"];
    textBgImageView.userInteractionEnabled = YES;
    [self addSubview:textBgImageView];
    
    
    
    UITextView *dlTextView = [[UITextView alloc] initWithFrame:CGRectMake(kAutoWidth(30), kAutoWidth(18), textBgImageView.width - kAutoWidth(30) *2, kAutoWidth(35))];
    dlTextView.delegate = self;
    dlTextView.textColor = kDLNormalBlackColor;
    dlTextView.keyboardType = UIKeyboardTypeDefault;
    dlTextView.returnKeyType = UIReturnKeySend;
//    dlTextView.backgroundColor = kColorRGB(240, 240, 240);
//    dlTextView.backgroundColor = kDLMachineTableAndCellBgColor;
    dlTextView.backgroundColor = [UIColor clearColor];

//    dlTextView.layer.cornerRadius = kAutoWidth(17.5);
//    dlTextView.layer.masksToBounds = YES;
//    dlTextView.delegate = self;
    [textBgImageView addSubview:dlTextView];
    self.dlTextView = dlTextView;

    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.text = @"请输入您想询问的内容";
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.textColor = kColorRGB(155, 155, 155);
//    placeHolderLabel.textColor = kColorRGB(30, 108, 227);
    [placeHolderLabel sizeToFit];
    [dlTextView addSubview:placeHolderLabel];//这句很重要不要忘了

    dlTextView.font = kBoldFont(kAutoWidth(15));
    placeHolderLabel.font = kBoldFont(kAutoWidth(15));
    [dlTextView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
    
    UIButton *changeInputTypeButton = [UIButton buttonWithType:0];
    changeInputTypeButton.frame = CGRectMake(kScreenWidth - kAutoWidth(50), 22, 40, 40);

    [changeInputTypeButton setImage:[UIImage imageNamed:@"machine_icn_voice"] forState:UIControlStateNormal];

    [self addSubview:changeInputTypeButton];
    [changeInputTypeButton addTarget:self action:@selector(changeInputTypeButtonClick:) forControlEvents:UIControlEventTouchUpInside];

    UIView *voiceView = [UIView new];
    voiceView.frame = CGRectMake(kAutoWidth(12.5), kAutoWidth(13 + 6.25), kAutoWidth(296.5), kAutoWidth(46));
    [self addSubview:voiceView];
    voiceView.layer.cornerRadius = voiceView.height / 2;
    voiceView.clipsToBounds = YES;
    self.voiceView = voiceView;

    UIImageView *imageV = [UIImageView new];
    imageV.backgroundColor = [UIColor whiteColor];
    imageV.frame = CGRectMake(0, 0, voiceView.width, voiceView.height);
    [voiceView addSubview:imageV];
    imageV.image = [UIImage sd_animatedGIFNamed:@"voiceInput"];
    self.imageV = imageV;
    
    voiceView.hidden = YES;

//    NSMutableArray *imgArray = [NSMutableArray array];
//    for (NSInteger i = 0; i < 7; i++) {
//        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"voice0%ld.png",i + 1]];
//        [imgArray addObject:image];
//    }
//    imageV.animationImages = imgArray;
//    imageV.animationDuration = 7*0.15;
//    imageV.animationRepeatCount = 0;
}

- (void) changeInputTypeButtonClick:(UIButton *)button {
    
    //检查麦克风权限是否开启
    [self checkMakefengquanxian];
    
    if (self.microphoneState == 1 || self.microphoneState == 2) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"未授权，请到手机->设置->德羲智语->麦克风，开启麦克风权限" duration:2 position:CSToastPositionCenter];
        return;
    } else {
        NSLog(@"麦克风可用");
    }
    
    NSLog(@"给我翻译一下，到底什么是他妈的惊喜？什么是-他妈的-惊喜?");
    if (self.dlTextView.isFirstResponder) {
        [self.dlTextView resignFirstResponder];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.26 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.voiceView.hidden = NO;
        });
    } else {
        self.voiceView.hidden = NO;
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"keyboardChangeInputType" object:nil];
    
    [self openIFly];
}
- (void) checkMakefengquanxian {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        switch (authStatus) {
            case AVAuthorizationStatusNotDetermined:{
                NSLog(@"没有询问是否开启麦克风");
                self.microphoneState = 0;
                break;
            }
            case AVAuthorizationStatusRestricted:{
                NSLog(@"未授权，家长限制");
                self.microphoneState = 1;
                break;
            }
            case AVAuthorizationStatusDenied:{
                NSLog(@"玩家未授权");
                self.microphoneState = 2;
                break;
            }
            case AVAuthorizationStatusAuthorized:{
                NSLog(@"玩家授权");
                self.microphoneState = 3;
                break;
            }
         default:
             break;
        }
}

- (void) openIFly {
    //创建语音识别对象
    _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
    _iFlySpeechRecognizer.delegate = self;
    //设置识别参数
    //设置为听写模式
    [_iFlySpeechRecognizer setParameter: @"iat" forKey: [IFlySpeechConstant IFLY_DOMAIN]];
    //asr_audio_path 是录音文件名，设置value为nil或者为空取消保存，默认保存目录在Library/cache下。
    [_iFlySpeechRecognizer setParameter:@"iat.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    //启动识别服务
    [_iFlySpeechRecognizer startListening];
    
    if ([_iFlySpeechRecognizer startListening]) {
        NSLog(@"开始识别");
        self.voiceView.hidden = NO;
        self.resultStringFromJson = @"";
    } else {
        NSLog(@"识别失败");
        self.voiceView.hidden = YES;
    }
}
//识别结果返回代理
- (void) onResults:(NSArray *) results isLast:(BOOL)isLast{
    //    NSLog(@"********识别结果返回代理，识别结果是：%@是否是最后一句:%d", results, isLast);
    
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    
    //持续拼接语音内容
    self.resultStringFromJson = [self.resultStringFromJson stringByAppendingString:[ISRDataHelper stringFromJson:resultString]];
    NSLog(@"self.resultStringFromJson = %@",self.resultStringFromJson);
    
    if (self.resultStringFromJson.length > 0) {
        
        self.voiceView.hidden = YES;
        [self.iFlySpeechRecognizer destroy];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"iflyDidTransformVoiceToString" object:self.resultStringFromJson];
    } else {
        
        kShowRequestMsg(@"小语好像没听到您的声音哦~");
        self.voiceView.hidden = YES;
    }
}
//识别会话结束返回代理
- (void)onCompleted: (IFlySpeechError *) error{
    NSLog(@"********识别会话结束返回代理:%@", error);
}
//停止录音回调
- (void) onEndOfSpeech{
    NSLog(@"********停止录音回调");
}
//开始录音回调
- (void) onBeginOfSpeech{
    NSLog(@"********开始录音回调");
}
//音量回调函数
- (void) onVolumeChanged: (int)volume{
    NSLog(@"********音量回调函数%d",volume );
    
    if (!self.imageV.isAnimating) {
        [self.imageV startAnimating];
    }
    
    if (volume == 0) {
        [self.imageV stopAnimating];
    }
}
//会话取消回调
- (void) onCancel{
    NSLog(@"********会话取消回调");
}


- (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if ([text isEqualToString:@"\n"]) {
        
        NSString *temp = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if ([temp length] == 0) {
            NSLog(@"全是空格");
            return NO;
        }
        NSString *newString = [self removeSpaceAndNewline:textView.text];
        
        if ([_delegate respondsToSelector:@selector(dlTextViewShouleReturn:)]) {
            [_delegate dlTextViewShouleReturn:newString];
        }
        return NO;
    }
    return YES;
}
- (NSString *)removeSpaceAndNewline:(NSString *)str{
    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
